package juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <pre>类名: LiveLockTest</pre>
 * <pre>描述: 活锁</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/11/5 15:28</pre>
 * <pre>作者: chenwb</pre>
 */
public class LiveLockTest {

	private static ReentrantLock lock1 = new ReentrantLock();
	private static ReentrantLock lock2 = new ReentrantLock();

	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(() -> {
			for (; ; ) {
				if (lock1.tryLock()) {
					try {
						if (lock2.tryLock()) {
							try {
								System.out.println("t1 同时获取lock1、lock2");
							} finally {
								lock2.unlock();
							}
						}
					} finally {
						lock1.unlock();
					}
				}
			}
		});
		Thread t2 = new Thread(() -> {
			for (; ; ) {
				if (lock2.tryLock()) {
					try {
						if (lock1.tryLock()) {
							try {
								System.out.println("t2 同时获取lock1、lock2");
							} finally {
								lock1.unlock();
							}
						}
					} finally {
						lock2.unlock();
					}
				}
			}
		});
		t1.start();
		t2.start();
		t1.join();
		t2.join();
	}
}
